import urllib
from elementtree.ElementTree import XML


def XMLRequest(url, data):
    return XMLResponse(urllib.urlopen(url, urllib.urlencode(data)).read())
    

class XMLResponse(object):
    "An object that simplifies flat XML documents (no element nesting)."

    def __init__(self, xml):
        self.xml = XML(xml)
        self._build_attrs()

    def _build_attrs(self):
        for node in self.xml.getchildren():
            setattr(self, node.tag, node.text)


class Response(object):
    "A generic gateway response"

    def __init__(self, success, message, raw_data, **options):
        self.success = success
        self.message = message
        self.data = raw_data
        self.authorization = options.pop('authorization', None)
        for k, v in options.items():
            setattr(self, k, v)

    def __unicode__(self):
        if self.success:
            success_msg = "Success"
        else:
            success_msg = "Failed"
        return u'%s (%s)' % (success_msg, self.message)
        
    def __repr__(self):
        return u'<merchant.%s: %s>' % (self.__class__.__name__, unicode(self))